from flask import Blueprint, render_template, session, redirect, url_for, flash,request
from functools import wraps
from db_utils import DbUtils
from models import Category, Article,db
from flask_sqlalchemy import SQLAlchemy

admin_bp = Blueprint('admin', __name__)

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            flash('请先登录', 'warning')
            return redirect(url_for('home.login'))
        return f(*args, **kwargs)
    return decorated_function

# 添加文章路由
@admin_bp.route('/add_article', methods=['GET', 'POST'])
@login_required
def add_article():
    if request.method == 'POST':
        try:
            # 表单验证
            title = request.form.get('title')
            content = request.form.get('content')
            category_id = request.form.get('category_id')
            
            if not title or not content:
                flash('标题和内容不能为空', 'danger')
                return redirect(url_for('admin.add_article'))
            
            # 创建新文章
            new_article = Article(
                title=title,
                content=content,
                category_id=category_id if category_id else None,
                author_id=session['user_id']
            )
            
            db.session.add(new_article)
            db.session.commit()
            flash('文章发表成功', 'success')
            return redirect(url_for('admin.admin_articles'))
            
        except Exception as e:
            db.session.rollback()
            print(f"Error adding article: {str(e)}")
            flash('文章发表失败', 'danger')
    
    # 获取分类列表
    categories = Category.query.all()
    return render_template('admin/add_article.html',
                         categories=categories,
                         nickname=session.get('user_nickname'))

@admin_bp.route('/articles')
@login_required
def admin_articles():
    user_id = session['user_id']
    db = DbUtils()
    try:
        articles = db.query("""
            SELECT a.*, c.name AS category_name 
            FROM articles a
            LEFT JOIN categories c ON a.category_id = c.id
            WHERE a.author_id = %s
            ORDER BY a.create_date DESC
        """, (user_id,)) or []
        
        return render_template('admin/articles.html', 
                            articles=articles,
                            nickname=session.get('user_nickname'))
    except Exception as e:
        print(f"Error in admin_articles: {str(e)}")
        return render_template('shared/500.html'), 500
    finally:
        db.close()
#  删除文章
@admin_bp.route('/articles/delete/<int:article_id>', methods=['POST'])
@login_required
def delete_article(article_id):
    user_id = session['user_id']
    db = DbUtils()
    try:
        # 验证文章归属
        article = db.query("SELECT id FROM articles WHERE id = %s AND author_id = %s", 
                         (article_id, user_id))
        if not article:
            flash('文章不存在或无权操作', 'danger')
            return redirect(url_for('admin.admin_articles'))
        
        # 执行删除
        affected = db.execute("DELETE FROM articles WHERE id = %s", (article_id,))
        if affected > 0:
            flash('文章删除成功', 'success')
        else:
            flash('文章删除失败', 'danger')
        return redirect(url_for('admin.admin_articles'))
    except Exception as e:
        print(f"Error in delete_article: {str(e)}")
        return render_template('shared/500.html'), 500
    finally:
        db.close()

@admin_bp.route('/edit_article/<int:article_id>', methods=['GET', 'POST'])
@login_required
def edit_article(article_id):
    user_id = session['user_id']
    db = DbUtils()
    try:
        # 验证文章归属
        article = db.query("""
            SELECT a.*, c.name AS category_name 
            FROM articles a
            LEFT JOIN categories c ON a.category_id = c.id
            WHERE a.id = %s AND a.author_id = %s
        """, (article_id, user_id))
        
        if not article:
            flash('文章不存在或无权操作', 'danger')
            return redirect(url_for('admin.admin_articles'))
        
        article = article[0]  # 获取第一个结果

        if request.method == 'POST':
            # 处理表单提交
            title = request.form.get('title')
            content = request.form.get('content')
            category_id = request.form.get('category_id')

            # 执行更新
            affected = db.execute("""
                UPDATE articles 
                SET title=%s, content=%s, category_id=%s 
                WHERE id=%s AND author_id=%s
            """, (title, content, category_id, article_id, user_id))
            
            if affected > 0:
                flash('文章更新成功', 'success')
                return redirect(url_for('admin.admin_articles'))
            else:
                flash('文章更新失败', 'danger')

        # 获取分类列表用于下拉菜单
        categories = db.query("SELECT id, name FROM categories")
        return render_template('admin/edit_article.html',
                            article=article,
                            categories=categories,
                            nickname=session.get('user_nickname'))
        
    except Exception as e:
        print(f"Error in edit_article: {str(e)}")
        return render_template('shared/500.html'), 500
    finally:
        db.close()
